//
//  AddItemViewController.swift
//  memo
//
//  Created by fly on 2019/10/12.
//  Copyright © 2019 Xiang HongFei. All rights reserved.
//

import UIKit
import UserNotifications
import MessageUI

protocol AddItemViewControllerDelegate: class {
    func AddItemViewController(_controller:AddItemViewController,endAdding item:TodoItem)
    func AddItemViewController(_controller:AddItemViewController,endEditing item:TodoItem)
    func AddItemViewController(_controller:AddItemViewController,enddelete item:TodoItem)
}

class AddItemViewController: UITableViewController ,UITextFieldDelegate{
    weak var delegatr: AddItemViewControllerDelegate?
    
    var itemToEdit : TodoItem?
    var dueDate = Date()
    var datePickerVisible = false
    var n = 0
    
    
    func showDatePicker() {
        datePickerVisible = true
        
        let indexPathDatePicker = IndexPath(row: 2, section: 1)
        tableView.insertRows(at: [indexPathDatePicker], with: .fade)
        
    }
    

    @IBOutlet weak var orderLabe: UILabel!
    @IBOutlet weak var delet: UIBarButtonItem!
    @IBOutlet weak var confirm: UIBarButtonItem!
    @IBOutlet weak var repertoryLabel: UILabel!
    @IBOutlet weak var datePicker: UIDatePicker!
    @IBOutlet weak var datePickerCell: UITableViewCell!
    @IBOutlet weak var remindSwitch: UISwitch!
    @IBOutlet weak var dueDateLabel: UILabel!
    @IBOutlet weak var doneBarButton: UIBarButtonItem!
    @IBOutlet weak var inputTextFiled: UITextField!
    @IBAction func cancel(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }
    @IBAction func commit(_ sender: Any) {
        if let item = itemToEdit {
            item.text = inputTextFiled.text!
            item.dueDate = dueDate
            item.scheduleNotification()
            item.repertory = repertoryLabel.text!
            delegatr?.AddItemViewController(_controller: self, endEditing: item)
        } else {
            let item = TodoItem(text: inputTextFiled.text!, checked: false)
            item.text = inputTextFiled.text!
            item.checked = false
            item.dueDate = dueDate
            item.scheduleNotification()
            item.repertory = repertoryLabel.text!
            delegatr?.AddItemViewController(_controller: self, endAdding: item)
            
        }
        dismiss(animated: true, completion: nil)
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        if let item = itemToEdit {
            title = "编辑宠物信息"
            inputTextFiled.text = item.text
            dueDate = item.dueDate
            repertoryLabel.text = item.repertory
        }else{
            title = "新建宠物"
            confirm.isEnabled = false
            delet.isEnabled = false
        }
        

    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewDidLoad()
        inputTextFiled.becomeFirstResponder()
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let oldStr = textField.text! as NSString
        let newStr = oldStr.replacingCharacters(in: range, with: string)
        doneBarButton.isEnabled = newStr.count > 0
        
        
        return true
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 1 && indexPath.row == 2 {
            return datePickerCell
        } else {
            return super.tableView(tableView, cellForRowAt: indexPath)
        }
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 1 && datePickerVisible {
            return 3
        } else {
            return super.tableView(tableView, numberOfRowsInSection: section)
        }
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 1 && indexPath.row == 2 {
            return 217
        } else {
            return super.tableView(tableView, heightForRowAt: indexPath)
        }
    }
    
    override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
        if indexPath.section == 1 && indexPath.row == 1 {
            return indexPath
        } else {
            return nil
        }
    }
    
    override func tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: IndexPath) -> Int {
        var newIndexPath = indexPath
        if indexPath.section == 1 && indexPath.row == 2 {
            newIndexPath = IndexPath(row: 0, section: indexPath.section)
        }
        return super.tableView(tableView, indentationLevelForRowAt: newIndexPath)
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        if indexPath.section == 1 && indexPath.row == 1 {
            showDatePicker()
        }
    }
    
    @IBAction func enter(_ sender: Any) {
        n = Int(repertoryLabel.text!) ?? 0
        n += 1
        repertoryLabel.text = "\(n)"
    }
    @IBAction func come(_ sender: Any) {
        n = Int(repertoryLabel.text!) ?? 0
        if n > 0 {
            n -= 1
            repertoryLabel.text = "\(n)"
        }
    }
    @IBAction func delet(_ sender: Any) {
        if let item = itemToEdit {
            let alert = UIAlertController(title: "提示", message: "请确认是否删除", preferredStyle: .alert)
                   let atnOk = UIAlertAction(title: "确认", style: .cancel, handler: {(alert:UIAlertAction) -> Void in
                    self.delegatr?.AddItemViewController(_controller: self, enddelete: item)
                    self.dismiss(animated: true, completion: nil)
                   })
            let btnOk = UIAlertAction(title: "取消", style: .default, handler: nil)
            alert.addAction(atnOk)
            alert.addAction(btnOk)
            self.present(alert, animated: true, completion: nil)
        }
    }

    
    @IBAction func addOrder(_ sender: Any) {
        var n = Int(orderLabe.text!) ?? 0
        n += 1
        orderLabe.text = "\(n)"
    }
    @IBAction func subOrder(_ sender: Any) {
        var n = Int(orderLabe.text!) ?? 0
        if n > 0 {
            n -= 1
            orderLabe.text = "\(n)"
        }
    }

    func configuredMailComposeViewController() -> MFMailComposeViewController {
        
     let mailComposeVC = MFMailComposeViewController()
        mailComposeVC.mailComposeDelegate = self as! MFMailComposeViewControllerDelegate
            
     //设置邮件地址、主题及正文
     mailComposeVC.setToRecipients(["1668141113@qq.com"])
     mailComposeVC.setSubject("订购")
        mailComposeVC.setMessageBody("定购" + (inputTextFiled.text ?? "") + (orderLabe.text ?? ""), isHTML: false)
            
     return mailComposeVC
        
    }
    
    func showSendMailErrorAlert() {

        let sendMailErrorAlert = UIAlertController(title: "无法发送邮件", message: "您的设备尚未设置邮箱，请在“邮件”应用中设置后再尝试发送。", preferredStyle: .alert)
        sendMailErrorAlert.addAction(UIAlertAction(title: "确定", style: .default) { _ in })
        self.present(sendMailErrorAlert, animated: true){}
     
    }
    
    @IBAction func order(_ sender: Any) {
        if inputTextFiled.isEditing {
            if MFMailComposeViewController.canSendMail() {
             let mailComposeViewController = configuredMailComposeViewController()
                self.present(mailComposeViewController, animated: true, completion: nil)
            } else {
             self.showSendMailErrorAlert()
            }
        }
    }
    func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
            
     switch result.rawValue {
     case MFMailComposeResult.cancelled.rawValue:
      print("取消发送")
     case MFMailComposeResult.sent.rawValue:
      print("发送成功")
     default:
      break
     }
        self.dismiss(animated: true, completion: nil)
            
    }
    // MARK: - Table view data source


    /*
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)

        // Configure the cell...

        return cell
    }
    */

    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
